package cn.wgx.activiti.demo.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.impl.form.DateFormType;
import org.activiti.engine.impl.form.StringFormType;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

@RestController
@RequestMapping("/")
public class ActivitiCtrl extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(ActivitiCtrl.class);

    @Autowired
    ProcessEngine processEngine;
    @Autowired
    TaskService taskService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    RepositoryService repositoryService;

    List<ProcessDefinition> processDefinitions = Lists.newArrayList();

    List<ProcessInstance> instanceList  = Lists.newArrayList();


    private static String resource = "process/second.bpmn20.xml";

    @ApiOperation(value = "部署流程", tags = "1")
    @GetMapping("def")
    public Object definition(){
        //测试只部署一个
        if(processDefinitions!=null && processDefinitions.size() > 0){
            return returnData(processDefinitions.get(0).getName());
        }
        ProcessDefinition processDefinition = getProcessDefinition();
        boolean add = true;
        for(ProcessDefinition processDefinition1 : processDefinitions) {
            if (processDefinition.getId().equals(processDefinition1.getId())) {
                add = false;
            }
        }
        if(add){
            processDefinitions.add(processDefinition);
        }
        return returnData(processDefinition.getName());
    }

    @ApiOperation(value = "启动流程", tags = "2")
    @GetMapping("start")
    public Object startPro(){
        if(processDefinitions != null && processDefinitions.size() > 0){
            ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitions.get(0).getId());
            instanceList.add(processInstance);
            return returnData(processInstance.getId());
        }
        return  returnData("没有部署流程图");
    }

    @ApiOperation(value = "获取任务列表", tags = "3")
    @GetMapping("getProcessList")
    public Object getProcessList(){
        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().list();
//        list.get(0).
        return returnData(list);
    }


    @ApiOperation(value = "获取任务列表", tags = "3")
    @GetMapping("getTasks")
    public Object getTasks(){
        TaskService taskService = processEngine.getTaskService();
        List<Task> list = taskService.createTaskQuery().list();
        List list1 = Lists.newArrayList();
        for(Task task: list){
            list1.add(task.getId());
        }
        return returnData(list1);
    }

    @ApiOperation(value = "获取处理任务参数", tags = "4")
    @GetMapping("getProParam")
    public Object getProParam(String id){
        Task task = getTaskById(id);
        FormService formService = processEngine.getFormService();
        TaskFormData taskFormData = formService.getTaskFormData(task.getId());
        List<FormProperty> formProperties = taskFormData.getFormProperties();
        return formProperties;
    }

    @ApiOperation(value = "处理任务", tags = "5" ,notes = "JSON body,必填 id,其他字段为接口getProParam获取")
    @PostMapping("pro")
    public Object pro(@RequestBody Map<String, Object> map){
        Task task = getTaskById(map.get("id").toString());
        taskService.complete(task.getId(), map);
        ProcessInstance processInstance = getProcessInstanceById(task.getProcessInstanceId());
        processInstance = processEngine.getRuntimeService()
                .createProcessInstanceQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();
        return processInstance;
    }

    private ProcessDefinition getProcessDefinition() {
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        deploymentBuilder.addClasspathResource(resource);
        Deployment deployment = deploymentBuilder.deploy();
        String deploymentId = deployment.getId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        logger.info("流程定义文件{}, 流程ID是{}", processDefinition.getName(), processDefinition.getId());
        return processDefinition;
    }

    private ProcessInstance getProcessInstanceById(String id){
        for(ProcessInstance processInstance: instanceList){
            if(processInstance.getId().equals(id)){
                return processInstance;
            }
        }
        return null;
    }

    private Task getTaskById(String id){
        List<Task> list = taskService.createTaskQuery().list();
        for(Task task: list){
            if(task.getId().equals(id)){
                return task;
            }
        }
        return null;
    }



    //wuyong
    private void processTask(ProcessInstance processInstance) throws ParseException {
        while(processInstance != null && !processInstance.isEnded()){
            List<Task> list = taskService.createTaskQuery().list();
            Scanner scanner = new Scanner(System.in);
            for(Task task: list){
                logger.info("正在处理任务 [{}]", task.getName());
                FormService formService = processEngine.getFormService();
                TaskFormData taskFormData = formService.getTaskFormData(task.getId());
                List<FormProperty> formProperties = taskFormData.getFormProperties();
                Map<String, Object> map = Maps.newHashMap();
                for(FormProperty formProperty: formProperties){
                    String line = "";
                    if(StringFormType.class.isInstance(formProperty.getType())){
                        logger.info("请输入[{}]:", formProperty.getName());
                        line = scanner.nextLine();
                        map.put(formProperty.getId(), line);
                    }else if(DateFormType.class.isInstance(formProperty.getType())){
                        logger.info("请输入[{}],格式: yyyy-MM-dd", formProperty.getName());
                        line = scanner.nextLine();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        map.put(formProperty.getId(), sdf.parse(line));
                    }
                    logger.info("您输入的是{}", line);
                }
                taskService.complete(task.getId(), map);
                processInstance = processEngine.getRuntimeService()
                        .createProcessInstanceQuery()
                        .processInstanceId(processInstance.getId())
                        .singleResult();
            }

        }
    }





}
